import tool from '../modules/tool'
const controls = tool.cControls
const controls_settings = controls.settings
import { useStore } from '../modules/store'
const store = useStore()

export default async (reloadPage, handleError) => {

    const status = {
        data: {},
        async get(loading = true) {
            let re = await tool.requestData('/question/AIParse/getDisplay', {}, {}, 'get', loading)
            if (re.status) {
                this.data = re.data
                this.trySetAuto()
            } else {
                throw re.content
            }
        },
        autoRefreshTimer: null,
        trySetAuto() {
            if (this.autoRefreshTimer != null) return
            status.autoRefreshTimer = setInterval(async () => {
                await status.get(false)
                reloadPage()
                if (status.data.running) {

                } else {
                    clearInterval(status.autoRefreshTimer)
                    this.autoRefreshTimer = null
                }
            }, 5000);
        },
        page: 0,
        selectedFinished: null,
        handleSelectFinished(item) {
            this.selectedFinished = item
            this.page = 1
            reloadPage()
        }
    }

    await status.get()

    const upload = {
        file: null,
        answerFile: null,
        categoryId: null,
        categoryName: null,
        paperName: '',
        async selectFile() {
            let re = await tool.selectFiles(['doc', 'docx', 'pdf'], 1)
            if (re && re.length) {
                this.file = re[0]
                reloadPage()
            }
        },
        async selectAnswerFile() {
            let re = await tool.selectFiles(['doc', 'docx', 'pdf'], 1)
            if (re && re.length) {
                this.answerFile = re[0]
                reloadPage()
            }
        },
        reset() {
            this.file = null
            this.answerFile = null
            this.paperName = ''
            this.categoryId = null
            this.categoryName = null
        },
        async selectCategory() {
            let catelst = await tool.requestData('/category/getList', {}, {}, 'get')
            if (catelst.status) {
                catelst = (() => {
                    let re = []
                    for (let i = 0; i < catelst.data.length; i++) {
                        re.push({
                            value: catelst.data[i].id,
                            title: catelst.data[i].name
                        })
                    }
                    return re
                })()
                store.showFormDialog('选择类别', [], [
                    {
                        field: 'categoryId',
                        title: '类别',
                        type: catelst
                    }
                ], {
                    categoryId: this.categoryId
                }, false, (e) => {
                    this.categoryId = e.categoryId
                    for (let i = 0; i < catelst.length; i++) {
                        if (catelst[i].value === e.categoryId) {
                            this.categoryName = catelst[i].title
                            break
                        }
                    }
                    store.hideFormDialog()
                    reloadPage()
                }, true, () => store.hideFormDialog())
            } else {
                tool.toast.error(catelst.content)
            }
        },
        inputPaperName() {
            store.showFormDialog('输入试卷名称', [], [
                {
                    field: 'paperName',
                    title: '试卷名称',
                    type: 'singleText'
                }
            ], {
                paperName: this.paperName
            }, false, (e) => {
                this.paperName = e.paperName
                store.hideFormDialog()
                reloadPage()
            }, true, () => store.hideFormDialog())
        }
    }

    const parsed = {
        data: {},
        async get() {
            let re = await tool.requestData('/question/AIParse/getDisplay', {}, {}, 'get')
            if (re.status) {
                this.data = re.data.finishedParseDocList
            } else {
                throw re.content
            }
        },
        selected: {
            item: undefined,
            async get(item) {
                await tool.flow(async () => {
                    this.item = item
                    let re = await tool.requestData(`/file/download/${this.item.downloadFileName}`, {}, {}, 'get')
                    if (!re) throw '请求不到文件'
                    if (re.status === 0) throw re.content
                    this.parsedFile = re
                    this.selectedQuestionIndex = 0
                    if (!this.getSelectedQuestionItem()) {
                        this.item = undefined
                        throw '当前解析后的试卷没有题目'
                    }
                    tool.event.setItem('question-import', {
                        item,
                        data: re
                    })
                    tool.event.setItem('openPage', {
                        title1: '题目管理',
                        title2: '导入题目'
                    })
                }, err => {
                    store.showModal2('无法打开试卷', `${err}。是否删除此条记录？`, async () => {
                        await tool.flow(async () => {
                            await parsed.selected.deleteFinished(item.id)
                            await parsed.get()
                            await status.get()
                            reloadPage()
                        }, err => tool.toast.error(`${err}`))
                    }, true, () => {

                    })
                })
            },
            parsedFile: undefined,
            selectedQuestionIndex: 0,
            getSelectedQuestionItem() {
                return this.parsedFile.parsed[this.selectedQuestionIndex]
            },
            changeSelectedQuestionIndex(to) {
                if (to < 0) {
                    throw '已是第一个题'
                }
                if (to > this.parsedFile.parsed.length - 1) {
                    throw '已是最后一个题'
                }
                this.selectedQuestionIndex = to
                reloadPage()
            },
            async deleteFinished(id) {
                let re = await tool.requestData('/question/AIParse/deleteFinished', {}, {
                    id
                }, 'post')
                if (re.status) {

                } else {
                    throw re.content
                }
            }
        }
    }

    await parsed.get()

    const page = {
        current: 0,
        change(to) {
            this.current = to
            reloadPage()
        }
    }

    const selectedParsedFile = {
        selected(item) {
            this.item = item
            reloadPage()
        },
        item: undefined
    }

    const refresh = async () => {
        return {
            type: 1,
            // controls: [
            //     controls.button({
            //         title: '上传带解析的文件和查看待解析试卷队列',
            //         plain: !(page.current === 0),
            //         type: page.current === 0 ? 'primary' : '',
            //         callBack() {
            //             page.change(0)
            //         }
            //     }),
            //     controls.button({
            //         title: '查看解析完成的试卷',
            //         plain: !(page.current === 1),
            //         type: page.current === 1 ? 'primary' : '',
            //         callBack() {
            //             page.change(1)
            //         }
            //     }),
            // ],
            left: (() => {
                if (page.current === 0) return undefined
                return {
                    title: '已完成解析的试题',
                    list: parsed.data,
                    props: {
                        label: 'paperName',
                    },
                    callBack(e) {
                        if (!parsed.selected.parsedFile) {
                            parsed.selected.get(e)
                            return
                        }
                        store.showModal2('提示', '是否切换试卷？这样做会导致当前试卷编辑过的内容丢失。', () => {
                            parsed.selected.get(e)
                            store.hideModal2()
                        }, true, () => store.hideModal2())
                    }
                }
            })(),
            main: {
                tab: [
                    ...(() => {
                        if (selectedParsedFile.item !== undefined) {
                            return [
                                {
                                    title: '',
                                    topControls: [
                                        controls.button({
                                            title: '返回',
                                            leftIcon: 'arrowLeft',
                                            plain: false,
                                            async callBack() {
                                                selectedParsedFile.item = undefined
                                                reloadPage()
                                            }
                                        })
                                    ],
                                    data: {
                                        type: 'settings',
                                        list: [
                                            controls_settings.buttonGroup(`${selectedParsedFile.item.categoryInfo.name} ${selectedParsedFile.item.paperName} 的操作`, [
                                                controls_settings.button('删除', async () => {
                                                    store.showModal2('提示', `是否删除此条记录？`, async () => {
                                                        await tool.flow(async () => {
                                                            await parsed.selected.deleteFinished(selectedParsedFile.item.id)
                                                            selectedParsedFile.item = undefined
                                                            await parsed.get()
                                                            await status.get()
                                                            reloadPage()
                                                        }, err => tool.toast.error(`${err}`))
                                                    }, true, () => {

                                                    })
                                                }),
                                                controls_settings.button('查看', async () => {
                                                    await tool.flow(async () => {
                                                        await parsed.selected.get(selectedParsedFile.item)
                                                        selectedParsedFile.item = undefined
                                                        reloadPage()
                                                    }, err => tool.toast.error(`${err}`))
                                                })
                                            ])
                                        ]
                                    }
                                }
                            ]
                        }
                        if (page.current === 0) {
                            return [
                                {
                                    title: '',
                                    bottomControls: [],
                                    topControls: [
                                        ...(() => {
                                            if (status.page === 0) return [
                                                controls.button({
                                                    title: '刷新',
                                                    leftIcon: 'refresh',
                                                    type: 'primary',
                                                    async callBack() {
                                                        await tool.flow(async () => {
                                                            await status.get()
                                                            reloadPage()
                                                        }, err => {
                                                            tool.toast.error(`${err}`)
                                                        })
                                                    }
                                                }),
                                            ]
                                            if (status.page === 1) return [
                                                controls.button({
                                                    title: '返回',
                                                    leftIcon: 'arrowLeft',
                                                    async callBack() {
                                                        status.page = 0
                                                        reloadPage()
                                                    }
                                                }),
                                            ]
                                        })()
                                    ],
                                    data: {
                                        type: 'settings',
                                        list: [
                                            controls_settings.buttonGroup('状态信息', [
                                                controls_settings.button('状态', () => {

                                                }, 'text', status.data.running ? '正在进行' : '未进行'),
                                                ...(() => {
                                                    if (status.data.running) {
                                                        return [
                                                            // controls_settings.button('当前试卷正在进行进度', () => {

                                                            // }, 'text', `${parseInt(status.data.progress * 10000) / 100}%`),
                                                            controls_settings.button('已完成试卷数', () => {

                                                            }, 'text', status.data.finishedParseDocList.length),
                                                            controls_settings.button('未完成试卷数', () => {

                                                            }, 'text', status.data.preToParseDocList.length)
                                                        ]
                                                    }
                                                    return []
                                                })(),
                                            ]),
                                            ...(() => {
                                                let finished = controls_settings.buttonGroup('已完成解析的试卷列表', [
                                                    ...(() => {
                                                        let re = []
                                                        for (let i = 0; i < status.data.finishedParseDocList.length; i++) {
                                                            re.push(
                                                                controls_settings.button(`${status.data.finishedParseDocList[i].categoryInfo.name} ${status.data.finishedParseDocList[i].paperName}`, async () => {
                                                                    if (status.data.finishedParseDocList[i].status === -1) {
                                                                        store.showModal2('提示', `当前试卷未顺利完成解析，报错内容：${status.data.finishedParseDocList[i].err}。是否删除此条记录？`, async () => {
                                                                            await tool.flow(async () => {
                                                                                await parsed.selected.deleteFinished(status.data.finishedParseDocList[i].id)
                                                                                await parsed.get()
                                                                                await status.get()
                                                                                reloadPage()
                                                                            }, err => tool.toast.error(`${err}`))
                                                                        }, true, () => {

                                                                        })
                                                                        return
                                                                    }
                                                                    selectedParsedFile.selected(status.data.finishedParseDocList[i])
                                                                }, 'text', status.data.finishedParseDocList[i].status === -1 ? `错误 (${status.data.finishedParseDocList[i].err})` : `已完成`)
                                                            )
                                                        }
                                                        return re
                                                    })(),
                                                ])
                                                if (status.data.running) {
                                                    return [
                                                        controls_settings.buttonGroup('未完成解析的试卷列表', [
                                                            ...(() => {
                                                                if (!status.data.running) {
                                                                    return []
                                                                }
                                                                let re = []
                                                                for (let i = 0; i < status.data.preToParseDocList.length; i++) {
                                                                    re.push(
                                                                        controls_settings.button(`${status.data.preToParseDocList[i].categoryInfo.name} ${status.data.preToParseDocList[i].paperName}`, () => {

                                                                        }, 'text', status.data.preToParseDocList[i].status === 0 ? '等待' : '正在解析')
                                                                    )
                                                                }
                                                                return re
                                                            })()

                                                        ]),
                                                        finished
                                                    ]
                                                } else {
                                                    return [finished]
                                                }
                                            })(),
                                            controls_settings.buttonGroup('添加', [
                                                controls_settings.button('选择试题文件', () => {
                                                    upload.selectFile()
                                                }, 'text', upload.file?.name || ''),
                                                controls_settings.button('选择答案文件', () => {
                                                    upload.selectAnswerFile()
                                                }, 'text', upload.answerFile?.name || ''),
                                                controls_settings.button('选择类别', () => {
                                                    upload.selectCategory()
                                                }, 'text', upload.categoryName || ''),
                                                controls_settings.button('输入试卷名称', () => {
                                                    upload.inputPaperName()
                                                }, 'text', upload.paperName || ''),
                                                controls_settings.button('提交', async () => {
                                                    try {
                                                        if (!upload.file) {
                                                            tool.toast.error('选择试题文件')
                                                            return
                                                        }
                                                        if (!upload.answerFile) {
                                                            tool.toast.error('选择答案文件')
                                                            return
                                                        }
                                                        if (!upload.categoryId) {
                                                            tool.toast.error('选择类别')
                                                            return
                                                        }
                                                        if (!upload.paperName) {
                                                            tool.toast.error('输入试题名称')
                                                            return
                                                        }
                                                        let upload_re_file = await tool.uploadFile('/file/upload', (() => {
                                                            let a = new FormData()
                                                            a.append('file', upload.file.file)
                                                            return a
                                                        })())
                                                        try {
                                                            upload_re_file = JSON.parse(upload_re_file)
                                                        } catch (error) {

                                                        }
                                                        if (!upload_re_file.status) throw upload_re_file.content
                                                        let fileName = upload_re_file.data
                                                        let upload_re_answerFile = await tool.uploadFile('/file/upload', (() => {
                                                            let a = new FormData()
                                                            a.append('file', upload.answerFile.file)
                                                            return a
                                                        })())
                                                        try {
                                                            upload_re_answerFile = JSON.parse(upload_re_answerFile)
                                                        } catch (error) {

                                                        }
                                                        if (!upload_re_answerFile.status) throw upload_re_answerFile.content
                                                        let answerFileName = upload_re_answerFile.data
                                                        let form = {
                                                            fileName,
                                                            answerFileName,
                                                            paperName: upload.paperName,
                                                            categoryId: upload.categoryId,
                                                            isEassy: false
                                                        }
                                                        let re = await tool.requestData('/question/AIParse/add', {}, form, 'post')
                                                        if (re.status) {
                                                            tool.toast.success('成功')
                                                            upload.reset()
                                                            reloadPage()
                                                            setTimeout(() => {
                                                                status.get()
                                                            }, 100);
                                                        } else {
                                                            throw re.content
                                                        }
                                                    } catch (error) {
                                                        tool.toast.error(error.toString())
                                                    }
                                                }),
                                                controls_settings.button('重置', () => {
                                                    upload.reset()
                                                    reloadPage()
                                                }),
                                            ]),
                                        ],
                                        callBack: async (e) => {
                                            console.log(e)
                                        },
                                    }
                                }
                            ]
                        }
                        if (page.current === 1) {
                            if (parsed.selected.parsedFile === undefined) {
                                return []
                            }
                            return [
                                {
                                    title: `${parsed.selected.item.paperName}（${parsed.selected.item.categoryInfo.name}）`,
                                    data: {
                                        type: 'questionPreview',
                                        item: parsed.selected.getSelectedQuestionItem(),
                                        images: parsed.selected.parsedFile.image,
                                        callBack(e) {
                                            console.log(e)
                                            if (e.op === 'deleteImage') {
                                                store.showModal2('提示', '是否删除这个图片？此操作不可恢复。', () => {
                                                    parsed.selected.parsedFile.image = [...parsed.selected.parsedFile.image.slice(0, e.index), ...parsed.selected.parsedFile.image.slice(e.index + 1)]
                                                    reloadPage()
                                                    store.hideModal2()
                                                }, true, () => {
                                                    store.hideModal2()
                                                })
                                            }
                                        }
                                    },
                                    bottomControls: [
                                        controls.button({
                                            title: '第一个',
                                            callBack() {
                                                parsed.selected.changeSelectedQuestionIndex(0)
                                            },
                                            disabled: parsed.selected.selectedQuestionIndex === 0
                                        }),
                                        controls.button({
                                            title: '上一个',
                                            callBack() {
                                                parsed.selected.changeSelectedQuestionIndex(parsed.selected.selectedQuestionIndex - 1)
                                            },
                                            disabled: parsed.selected.selectedQuestionIndex === 0
                                        }),
                                        controls.label({
                                            title: `${parsed.selected.selectedQuestionIndex + 1}/${parsed.selected.parsedFile.parsed.length}`
                                        }),
                                        controls.button({
                                            title: '下一个',
                                            callBack() {
                                                parsed.selected.changeSelectedQuestionIndex(parsed.selected.selectedQuestionIndex + 1)
                                            },
                                            disabled: parsed.selected.selectedQuestionIndex === (parsed.selected.parsedFile.parsed.length - 1)
                                        }),
                                        controls.button({
                                            title: '最后一个',
                                            callBack() {
                                                parsed.selected.changeSelectedQuestionIndex(parsed.selected.parsedFile.parsed.length - 1)
                                            },
                                            disabled: parsed.selected.selectedQuestionIndex === (parsed.selected.parsedFile.parsed.length - 1)
                                        }),
                                    ]
                                }
                            ]
                        }
                        return []
                    })()
                ]
            }
        }
    }

    return refresh
}